package com.cloudcc.mobile.view.dynamic.relevant;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.ChatIndexAdapter;
import com.cloudcc.mobile.adapter.ChatIndexAdapter.OnItemListener;
import com.cloudcc.mobile.entity.FavoriteFeed;
import com.cloudcc.mobile.entity.FeedFile;
import com.cloudcc.mobile.entity.Follow;
import com.cloudcc.mobile.entity.FollowerUser;
import com.cloudcc.mobile.entity.GetFollowerUserMessage;
import com.cloudcc.mobile.entity.GetRecordFollowUsers;
import com.cloudcc.mobile.entity.MyChatter;
import com.cloudcc.mobile.entity.MyChatterMessage;
import com.cloudcc.mobile.entity.OptionUser;
import com.cloudcc.mobile.entity.PraiseFeed;
import com.cloudcc.mobile.entity.addmicropost.Polls;
import com.cloudcc.mobile.entity.chatter.ChatterParamData;
import com.cloudcc.mobile.entity.comment.Comments;
import com.cloudcc.mobile.entity.comment.CommentsFile;
import com.cloudcc.mobile.entity.comment.RemoveMicroPostMessage;
import com.cloudcc.mobile.entity.handle.RemoveMicroPost;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.GetFollowerUserParser;
import com.cloudcc.mobile.parser.HandleParser;
import com.cloudcc.mobile.parser.MyChatterParser;
import com.cloudcc.mobile.parser.ReturnCodeParser;
import com.cloudcc.mobile.service.GetFollowService;
import com.cloudcc.mobile.service.MyChatterService;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.LoadingUtils;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.UserInfoActivity;
import com.cloudcc.mobile.view.dynamic.DynamicActivity;
import com.cloudcc.mobile.view.dynamic.SendTimeLineActivity;
import com.cloudcc.mobile.view.login.LoginNewActivity;
import com.cloudcc.mobile.weight.CustomListView;
import com.cloudcc.mobile.weight.CustomListView.OnLoadMoreListener;
import com.cloudcc.mobile.weight.CustomListView.OnRefreshListener;
import com.cloudcc.mobile.weight.LoadingView;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 在网页中查看记录详情时候的Chat页面
 * 
 * @author Administrator
 * 
 */
public class RelevantChatFragment extends Fragment {
	private ImageView sett, xinjian;
	private CustomListView listview;
	private TextView tvpinglunaqwqw;
	private MyChatterService service;
	private MyChatterMessage msg;
	private ChatIndexAdapter adapter;
	private List<MyChatter> total = new ArrayList<MyChatter>();
	private ChatterParamData chatterParamData;
	private RelativeLayout mmm;
	private LoadingView loadingview;
	private int skip = 0, page = 1, count = 0;
	private MyChatter myChatter;
	private String weizhiid;
	private int weizhi;
	private boolean isfavorited;
	int praisenum;
	boolean ispraised;
	public int notifyNum;
	private FrameLayout frame, framelayout;
	private ImageView no_wangluo;
	private View view;
	private Context context;
	private MyReceiver receiver;
	private boolean isCanGuanzhu = true;
	String id;
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case 1:
					adapter.changeData(total);
					page++;
					count++;
					break;
				case 0:
					adapter.changeData(total);
					listview.setAdapter(adapter);
					page++;
					count++;
					break;
				case -1:
					Tools.showInfo(getActivity(), "查询异常");
					break;
				case -2:
					Tools.showInfo(getActivity(), "连接超时，请稍后重试");
					break;
				case -3:
					Tools.showInfo(getActivity(), "查询失败");
					break;
				case 2:
					Tools.showInfo(getActivity(), "数据加载完成");
					break;
				default:
					listview.onLoadMoreComplete();
					listview.onRefreshComplete();
					loadingview.setVisibility(View.GONE);
					break;
				}
				listview.onLoadMoreComplete();

				listview.onRefreshComplete();
				listview.setCanRefresh(true);
				listview.setCanLoadMore(true);
				listview.setAutoLoadMore(true);
				loadingview.setVisibility(View.GONE);
				super.handleMessage(msg);
			} catch (Exception e) {
				Tools.handle(e);
			}
		}
	};
	private LinearLayout guanzhuChat;
	private TextView guanzhuName, fuhao;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		try {
			if (view == null) {
				view = inflater.inflate(R.layout.relevant_chat, null);
				context = getActivity();
			}
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
			setupView(view);
			addListener();
		} catch (Exception e) {
			Tools.handle(e);
		}
		return view;
	}

	private void setupView(View view) {
		receiver = new MyReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppContext.INDEXADAPTER_SHUAXIN);
		filter.addAction(AppContext.RECORD_ID_CHANGED_SHUAXIN);
		context.registerReceiver(receiver, filter);
		id = getActivity().getIntent().getStringExtra("web");
		LogUtils.d("webview", "关注id:" + id);
		frame = (FrameLayout) view.findViewById(R.id.indexframe);
		framelayout = (FrameLayout) view.findViewById(R.id.fragment);
		no_wangluo = (ImageView) view.findViewById(R.id.no_wangluo);
		guanzhuChat = (LinearLayout) view.findViewById(R.id.guanzhu_chat);
		guanzhuName = (TextView) view.findViewById(R.id.guanzhu_name);
		fuhao = (TextView) view.findViewById(R.id.fuhao);
		mmm = (RelativeLayout) view.findViewById(R.id.introduction);
		tvpinglunaqwqw = (TextView) view.findViewById(R.id.tvpinglunaqwqw);
		loadingview = (LoadingView) view.findViewById(R.id.loading_aa);
		sett = (ImageView) view.findViewById(R.id.sett);
		xinjian = (ImageView) view.findViewById(R.id.new_xj);
		listview = (CustomListView) view
				.findViewById(R.id.index_chatter_follower);
		listview.setDividerHeight(0);// 设置边框0无线
		listview.setCanRefresh(false);
		listview.setCanLoadMore(true);
		listview.setAutoLoadMore(true);
		service = new MyChatterService();
		adapter = new ChatIndexAdapter(getActivity());
		getGuanZhu();// 获取登陆者是否关注
		setDbData();
		onRefreshData();
		if (loadingview.getVisibility() == View.VISIBLE) {
			listview.setCanRefresh(false);
		}
	}

	private void setDbData() {
		DbUtils db = DbUtils.create(context,
				UserManager.getManager().getUser().userId + id);
		try {
			if (db.tableIsExist(MyChatter.class)) {
				total = db.findAll(MyChatter.class);
				for (int i = 0; i < total.size(); i++) {
					if (db.tableIsExist(Comments.class)) {
						List<Comments> commentlist = db.findAll(Selector.from(
								Comments.class).where("parendId", "=",
								total.get(i).getId()));
						if (commentlist != null) {
							for (int j = 0; j < commentlist.size(); j++) {
								CommentsFile commentsFile = db
										.findFirst(Selector.from(
												CommentsFile.class)
												.where("id",
														"=",
														commentlist.get(j)
																.getId()));
								if (commentsFile != null) {
									commentlist.get(j).setCommentsFile(
											commentsFile);
								}
							}
							total.get(i).setComments(commentlist);
						}
					}
					if (db.tableIsExist(FeedFile.class)) {
						List<FeedFile> feedFiles = db.findAll(Selector.from(
								FeedFile.class).where("parendId", "=",
								total.get(i).getId()));
						if (feedFiles != null) {
							total.get(i).setFeedFile(feedFiles);
						}
					}
					if (db.tableIsExist(Polls.class)) {
						List<Polls> polls = db.findAll(Selector.from(
								Polls.class).where("parendId", "=",
								total.get(i).getId()));
						if (polls != null && polls.size() > 0) {
							total.get(i).setPolls(polls);
						}
					}
					if (db.tableIsExist(OptionUser.class)) {
						List<Polls> p = total.get(i).getPolls();
						if (p != null && p.size() > 0) {
							for (int ii = 0; ii < p.size(); ii++) {
								List<OptionUser> optionUsers = db
										.findAll(Selector
												.from(OptionUser.class)
												.where("parendId",
														"=",
														p.get(ii)
																.getOptionIndex()
																+ p.get(ii)
																		.getParendId()));
								if (optionUsers != null
										&& optionUsers.size() > 0) {
									String[] oo = new String[optionUsers.size()];
									for (int jj = 0; jj < optionUsers.size(); jj++) {
										oo[jj] = optionUsers.get(jj).getWho();
									}
									total.get(i).getPolls().get(ii)
											.setOptionUsers(oo);
								} else {
									String[] pp = new String[0];
									total.get(i).getPolls().get(ii)
											.setOptionUsers(pp);
								}
							}
						}
					}
				}
				adapter.changeData(total);
				listview.setAdapter(adapter);
				listview.setCanRefresh(true);
				listview.setCanLoadMore(true);
				listview.setAutoLoadMore(true);
			}
		} catch (DbException e) {
			Tools.handle(e);
		}
	}

	/**
	 * 刷新获取数据或者刚进入软件的获取数据
	 */
	private void onRefreshData() {
		frame.setVisibility(View.GONE);
		framelayout.setVisibility(View.VISIBLE);
		listview.HideFooter();
		chatterParamData = new ChatterParamData();
		chatterParamData.setUserId(UserManager.getManager().getUser().userId);
		chatterParamData.setFeedSort(RunTimeManager.getInstance().getDynamicType());
		chatterParamData.setLimit(AppContext.limit);
		chatterParamData.setFeedId("");
		chatterParamData.setRecordId(id);
		chatterParamData.setQueryType("record");
		page = 1;
		count = 0;
		skip = count * 10;
		chatterParamData.setSkip(skip);
		String a = Json.toJson(chatterParamData);
		new getChatterr().execute(a);
	}

	class getChatterr extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			String data = params[0];
			String result = service.getChatters01(data);
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			msg = new MyChatterMessage();
			msg = MyChatterParser.getMyChatter(result);
			yiChang(result);
			if (!msg.isResult()) {
				handler.sendEmptyMessage(-3);
				return;
			}
			if (msg.getList().size() == 0 && total.size() == 0) {
				loadingview.setVisibility(View.GONE);
				frame.setVisibility(View.VISIBLE);
				no_wangluo.setVisibility(View.VISIBLE);
				framelayout.setVisibility(View.GONE);
				return;
			}
			if (msg.getList().size() == 0) {
				handler.sendEmptyMessage(2);
				return;
			}
			if (page == 1) {
				total.clear();
			}
			for (int i = 0; i < msg.getList().size(); i++) {
				if (msg.getList().get(i).getFeedType().equals("V")) {
					List<Polls> list = msg.getList().get(i).getPolls();
					if (list != null) {
						for (int j = 0; j < list.size(); j++) {
							Polls p = list.get(j);
							String[] a = p.getOptionUsers();
							if (a.length > 0) {
								for (int k = 0; k < a.length; k++) {
									if (UserManager.getManager().getUser().userId
											.equals(a[k])) {
										msg.getList().get(i).setTpflag(true);
									}
								}
							}
						}
					}
				}
			}
			total.addAll(msg.getList());
			if (page == 1) {
				DbUtils db = DbUtils.create(context, UserManager.getManager()
						.getUser().userId + id);
				try {
					if (db.tableIsExist(MyChatter.class)) {
						db.deleteAll(MyChatter.class);
					}
					if (db.tableIsExist(Polls.class)) {
						db.deleteAll(Polls.class);
					}
					if (db.tableIsExist(OptionUser.class)) {
						db.deleteAll(OptionUser.class);
					}
					if (db.tableIsExist(FeedFile.class)) {
						db.deleteAll(FeedFile.class);
					}
					if (db.tableIsExist(Comments.class)) {
						db.deleteAll(Comments.class);
					}
					if (db.tableIsExist(CommentsFile.class)) {
						db.deleteAll(CommentsFile.class);
					}
					db.saveAll(total);
					for (int j = 0; j < total.size(); j++) {
						// 文件 或者图片
						try {
							List<FeedFile> flist = total.get(j).getFeedFile();
							if (flist.size() > 0) {
								for (int l = 0; l < flist.size(); l++) {
									FeedFile file = new FeedFile();
									file = flist.get(l);
									file.setParendId(total.get(j).getId());
									db.save(file);
								}
							}
						} catch (Exception e1) {
							Tools.handle(e1);
						}
						// 评论
						try {
							List<Comments> list = total.get(j).getComments();// 如果有评论,
							if (list.size() > 0) {
								for (int k = 0; k < list.size(); k++) {
									Comments comments = new Comments();
									comments = list.get(k);
									comments.setParendId(total.get(j).getId());// 把这条chatter记录
									CommentsFile commentsFile = comments
											.getCommentsFile();
									if (commentsFile != null) {
										commentsFile.setId(comments.getId());
										db.save(commentsFile);
									}
									db.save(comments);
								}
							}
						} catch (Exception e1) {
							Tools.handle(e1);
						}
						// 投票
						try {
							List<Polls> plist = total.get(j).getPolls();// 如果有投票
							if (plist.size() > 0) {
								for (int i = 0; i < plist.size(); i++) {
									Polls p = new Polls();
									p = plist.get(i);
									p.setParendId(total.get(j).getId());
									String[] e = p.getOptionUsers();
									if (e != null && e.length > 0) {
										for (int q = 0; q < e.length; q++) {
											OptionUser o = new OptionUser();
											o.setWho(e[q]);
											o.setParendId(p.getOptionIndex()
													+ total.get(j).getId());
											db.save(o);
										}
									}
									db.save(p);
								}
							}
						} catch (Exception e) {
							Tools.handle(e);
						}
					}
				} catch (DbException e) {
					Tools.handle(e);
				}
			}
			if (page == 1) {
				handler.sendEmptyMessage(0);
			} else {
				handler.sendEmptyMessage(1);
			}
		}
	}

	public void yiChang(String result) {
		if (result == null || result.equals("NetworkError")) {
			handler.sendEmptyMessage(-1);
			if (total.size() == 0) {
				framelayout.setVisibility(View.GONE);
				frame.setVisibility(View.VISIBLE);
				no_wangluo.setVisibility(View.VISIBLE);
			}
			return;
		}
		if (result.equals("outTime")) {
			handler.sendEmptyMessage(-2);
			return;
		}
		String code = ReturnCodeParser.getReturnCode(result);
		if (code.equals("-2")) {
			Tools.showInfo(context, "登陆超时,请重新登陆");
			Intent intent = new Intent(context, LoginNewActivity.class);
			startActivity(intent);
			return;
		}
	}

	private void addListener() {
		guanzhuChat.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					if (isCanGuanzhu) {
						guanzhu();
						isCanGuanzhu = false;
					}
				} catch (UnsupportedEncodingException e) {
					Tools.handle(e);
				}
			}
		});
		tvpinglunaqwqw.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mmm.setVisibility(View.GONE);
				framelayout.setVisibility(View.VISIBLE);
			}
		});
		frame.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				loadingview.setVisibility(View.VISIBLE);
				frame.setVisibility(View.GONE);
				framelayout.setVisibility(View.VISIBLE);
				listview.HideFooter();
				chatterParamData = new ChatterParamData();
				chatterParamData
						.setUserId(UserManager.getManager().getUser().userId);
				chatterParamData.setFeedSort(AppContext.feedSort);
				chatterParamData.setLimit(AppContext.limit);
				chatterParamData.setFeedId("");
				chatterParamData.setRecordId(id);
				chatterParamData.setQueryType("record");
				count = 0;
				page = 1;
				skip = count * 10;
				chatterParamData.setSkip(skip);
				String a = Json.toJson(chatterParamData);
				new getChatterr().execute(a);
			}
		});
		sett.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getActivity().finish();
			}
		});
		xinjian.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(),
						SendTimeLineActivity.class);
				intent.putExtra("relevantId", id);
				getActivity().startActivity(intent);
			}
		});
		listview.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				onRefreshData();
			}
		});
		// 加载更多
		listview.setOnLoadListener(new OnLoadMoreListener() {
			@Override
			public void onLoadMore() {
				chatterParamData = new ChatterParamData();
				chatterParamData
						.setUserId(UserManager.getManager().getUser().userId);
				chatterParamData.setFeedSort(AppContext.feedSort);
				chatterParamData.setLimit(AppContext.limit);
				chatterParamData.setFeedId("");
				chatterParamData.setRecordId(id);
				chatterParamData.setQueryType("record");
				skip = count * 10;
				chatterParamData.setSkip(skip);
				String a = Json.toJson(chatterParamData);
				new getChatterr().execute(a);
			}
		});
		adapter.setOnItemtListener(new OnItemListener() {
			@Override
			public void xihuan(int position, View v) {
				v.setClickable(false);
				weizhiid = total.get(position).getId();
				AppContext.iszan = weizhiid;
				weizhi = position;
				ispraised = !total.get(position).isIspraised();

				total.get(weizhi).setIspraised(ispraised);
				String num = total.get(weizhi).getPraisenum();
				if (num == null || num.equals("")) {
					praisenum = 0;
				} else {
					praisenum = Integer.valueOf(num);
				}
				if (ispraised) {
					total.get(weizhi).setPraisenum((praisenum + 1) + "");
				} else {
					int pnum = praisenum - 1;
					if (pnum == 0) {
						total.get(weizhi).setPraisenum("");
					} else {
						total.get(weizhi).setPraisenum((praisenum - 1) + "");
					}
				}
				v.setClickable(true);
				adapter.changeData(total);
				PraiseFeed praiseFeed = new PraiseFeed();
				praiseFeed.setFeedId(total.get(position).getId());
				if (ispraised) {
					praiseFeed.setLikeOrDislike("1");
				} else {
					praiseFeed.setLikeOrDislike("-1");
				}
				String xihuan = Json.toJson(praiseFeed);
				new xihuanTask(v).execute(xihuan);
			}

			@Override
			public void shoucang(int position) {
				weizhiid = total.get(position).getId();
				AppContext.shoucang = weizhiid;
				weizhi = position;
				FavoriteFeed favoriteFeed = new FavoriteFeed();
				favoriteFeed.setFeedId(weizhiid);
				isfavorited = !total.get(position).isIsfavorited();
				if (isfavorited) {
					total.get(weizhi).setIsfavorited(true);
				} else {
					total.get(weizhi).setIsfavorited(false);
				}
				adapter.changeData(total);

				if (isfavorited) {
					favoriteFeed.setFavoriteOrUnfavorite("1");
				} else {
					favoriteFeed.setFavoriteOrUnfavorite("-1");
				}
				String shoucang = Json.toJson(favoriteFeed);
				new shoucangTask().execute(shoucang);// 联网收藏
			}

			@Override
			public void pinglun(int position) {// 评论
				myChatter = total.get(position);
				Intent intent = new Intent(getActivity(), DynamicActivity.class);
				intent.putExtra("myChatter", myChatter);
				startActivity(intent);
			}

			@Override
			public void shanchu(final int position) {
				if (!NetWork.detect(context)) {
					Tools.showInfo(context, "亲，请检查网络~");
					return;
				}
				if (total.get(position).getAuthorId()
						.equals(UserManager.getManager().getUser().userId)) {
					showDialog(position);
				}
			}

			@Override
			public void downloadpic(int position) {
				LoadingUtils loading = new LoadingUtils(context, total
						.get(position), position);
				loading.loadingFile();
			}

			@Override
			public void icon(int position) {
				weizhi = position;
				myChatter = total.get(position);
				Intent intent = new Intent(getActivity(),
						UserInfoActivity.class);
				intent.putExtra("userId", myChatter.getId());
				startActivity(intent);
			}

			@Override
			public void nicheng(int position) {
				myChatter = total.get(position);
				Intent intent = new Intent(getActivity(),
						UserInfoActivity.class);
				intent.putExtra("userId", myChatter.getId());
				startActivity(intent);
			}

			@Override
			public void btntoupiao(int position) {
				myChatter = total.get(position);
				Intent intent = new Intent(getActivity(), DynamicActivity.class);
				intent.putExtra("myChatter", myChatter);
				startActivity(intent);
			}

			@Override
			public void zhengti(int position) {
				myChatter = total.get(position);
				if (myChatter.getFeedType().equals("V")) {
					int a = myChatter.getPolls().size();
					Tools.i("chatindexfragment", a);
				}
				Intent intent = new Intent(getActivity(), DynamicActivity.class);
				intent.putExtra("myChatter", myChatter);
				startActivity(intent);
			}
		});
	}

	private void getGuanZhu() {
		GetRecordFollowUsers followUsers = new GetRecordFollowUsers();
		followUsers.setRecordId(id);
		String json = Json.toJson(followUsers);
		new GetGuanZhuTask().execute(json);
	}

	class GetGuanZhuTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			String json = params[0];
			GetFollowService service = new GetFollowService();
			String result = service.getRecordFollowUsers(json);
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			yiChang(result);
			GetFollowerUserMessage msg = GetFollowerUserParser
					.getfollowers(result);
			List<FollowerUser> flist = msg.getList();
			if (flist != null && flist.size() > 0) {
				for (int i = 0; i < flist.size(); i++) {
					String j = flist.get(i).getUserid();
					if (j.equals(UserManager.getManager().getUser().userId)) {
						guanzhuName.setText("取消关注");
						fuhao.setVisibility(View.GONE);
						return;
					}
				}
			}
			guanzhuName.setText("关注");
			fuhao.setVisibility(View.VISIBLE);
		}
	}

	protected void guanzhu() throws UnsupportedEncodingException {
		Follow follow = new Follow();
		if (guanzhuName.getText().toString().trim().equals("关注")) {
			follow.setFollowStatus("1");
		} else {
			follow.setFollowStatus("0");
		}
		follow.setFollowType("record");
		follow.setParentId(id);
		String json = Json.toJson(follow);
		String data = URLEncoder.encode(json, "utf-8");
		String url = UrlTools.url + UrlTools.url_path
				+ "serviceName=operateFollowRelation&data=" + data
				+ "&binding=" + AppContext.binding;
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {
					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						isCanGuanzhu = true;
						// {"result":true,"returnInfo":"","returnCode":"1"}
						try {
							String json = responseInfo.result;
							JSONObject jsonString = new JSONObject(json);
							boolean isResult = jsonString.getBoolean("result");
							if (isResult) {
								if (guanzhuName.getText().toString().trim()
										.equals("关注")) {
									guanzhuName.setText("取消关注");
									fuhao.setVisibility(View.GONE);
									Tools.showInfo(context, "关注成功");
								} else {
									guanzhuName.setText("关注");
									fuhao.setVisibility(View.VISIBLE);
									Tools.showInfo(context, "取消关注成功");
								}
							}
						} catch (JSONException e) {
							Tools.handle(e);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						isCanGuanzhu = true;
						if (guanzhuName.getText().toString().trim()
								.equals("关注")) {
							Tools.showInfo(context, "关注失败");
						} else {
							Tools.showInfo(context, "取消关注失败");
						}

					}
				});

	}

	class Ddialog {
		private TextView name;
	}

	protected void showDialog(final int position) {
		final Ddialog dd = new Ddialog();
		LayoutInflater inflater = getActivity().getLayoutInflater();
		View layout = inflater.inflate(R.layout.define_deleted, null);
		dd.name = (TextView) layout.findViewById(R.id.titletitle);
		dd.name.setText("确定删除这条微贴吗？");
		final AlertDialog builder = new AlertDialog.Builder(getActivity())
				.create();
		builder.setView(layout);
		builder.show();
		Button cancle = (Button) layout.findViewById(R.id.quxiaocanle);
		cancle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.cancel();
			}
		});
		Button sure = (Button) layout.findViewById(R.id.quedingsure);
		sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (total.get(position).getAuthorId()
						.equals(UserManager.getManager().getUser().userId)) {
					RemoveMicroPost remove = new RemoveMicroPost();
					remove.setFeedId(total.get(position).getId());
					weizhiid = total.get(position).getId();
					// 联网删帖
					String json = Json.toJson(remove);
					new MyTask().execute(json);
					// list里删除，
					total.remove(position);
					adapter.changeData(total);
					builder.cancel();
				}
			}
		});

	}

	class MyTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			String data = params[0];
			String json;
			List<NameValuePair> pairs = new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair("serviceName", "removeMicroPost"));
			pairs.add(new BasicNameValuePair("data", data));
			pairs.add(new BasicNameValuePair("binding", AppContext.binding));
			String url = UrlTools.url_path;
			json = NetWork.post(url, pairs);
			return json;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			try {
				yiChang(result);
				RemoveMicroPostMessage msg = HandleParser.removetiezi(result);
				boolean flag = msg.isResult();
				if (flag) {
					// 数据库删除
					DbUtils db = DbUtils.create(context, UserManager
							.getManager().getUser().userId + id);
					try {
						if (db.tableIsExist(MyChatter.class)) {
							db.deleteById(MyChatter.class, weizhiid);
						}
					} catch (Exception e) {
						e.printStackTrace();
						Tools.handle(e);
					}
				} else {
				}
			} catch (Exception e) {
				e.printStackTrace();
				Tools.handle(e);
			}
		}
	}

	public class xihuanTask extends AsyncTask<String, Void, String> {
		private RelativeLayout v;

		public xihuanTask(View v) {
			this.v = (RelativeLayout) v;
		}

		@Override
		protected String doInBackground(String... params) {
			String xihuan = params[0];
			List<NameValuePair> pairs = new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair("serviceName", "praiseFeed"));
			pairs.add(new BasicNameValuePair("data", xihuan));
			pairs.add(new BasicNameValuePair("binding", AppContext.binding));
			String url = UrlTools.url_path;
			String result = NetWork.post(url, pairs);
			return result;
		}
	}

	class shoucangTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			String shoucang = params[0];
			List<NameValuePair> pairs = new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair("serviceName", "favoriteFeed"));
			pairs.add(new BasicNameValuePair("data", shoucang));
			pairs.add(new BasicNameValuePair("binding", AppContext.binding));
			String url = UrlTools.url_path;
			String result = NetWork.post(url, pairs);
			return result;
		}
	}

	@Override
	public void onDestroy() {
		context.unregisterReceiver(receiver);
		super.onDestroy();
	}

	class MyReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(AppContext.INDEXADAPTER_SHUAXIN)) {
				onRefreshData();
			} else if (action.equals(AppContext.RECORD_ID_CHANGED_SHUAXIN)) {
				id = AppContext.record_id;
				onRefreshData();
			}
		}
	}
}